package com.java.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.java.entity.TodoList;
import com.java.utils.FileIo;
import com.java.utils.MyTools;

/**
* @ClassName: TodoDao
*
 */
public class TodoDao {

	public static List<TodoList> getTodos(){
		List<TodoList> list = new ArrayList<TodoList>();
		try {
			list = FileIo.read();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return list;
	}

	public static Map<String, List<TodoList>> getMap(){
		Map<String, List<TodoList>>  res = new HashMap<String, List<TodoList>>();
		List<TodoList> list = getTodos();
		for (TodoList todo : list) {
			List<TodoList> mlist = res.get(todo.getStartTime());
			if(null == mlist) {
				mlist = new ArrayList<TodoList>();
				mlist.add(todo);
			}else {
				mlist.add(todo);
			}
			res.put(todo.getStartTime(), mlist);
		}
		return res;
	}

	public static List<TodoList> getADay(String day){
		Map<String, List<TodoList>> map = getMap();
		return map.get(day);
	}

	public static void delTodo(String title) {
		try {
			List<TodoList> list = getTodos();
			if(null != list) {
				int index = getIndex(list, title);
				list.remove(index);
				save(list);
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

	public static void saveTodo(TodoList todo) {
		int index = 0;
		try {
			List<TodoList> list = getTodos();
			if(null == list) {
				list = new ArrayList<TodoList>();
			}
			index = list.size();
			todo.setId(index);
			todo.setCreateTime(MyTools.getNowDateTimeSub());
			list.add(todo);
			save(list);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

	public static void updateTodo(TodoList todo) {
		try {
			List<TodoList> list = getTodos();
			int index = getIndex(list, todo.getTitle());
			list.set(index, todo);
			save(list);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}
	
	private static void save(List<TodoList> list) {
		String str = JSON.toJSONString(list,
                JSONWriter.Feature.WriteNonStringValueAsString,
                JSONWriter.Feature.NullAsDefaultValue
        );
		try {
			FileIo.write(str);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}
	
	private static int getIndex(List<TodoList> list, String title) {
		if(null == list) {
			return 0;
		}
		for (int i = 0; i < list.size(); i++) {
			if(title.equals(list.get(i).getTitle())) {
				return i;
			}
		}
		return 0;
	}
}
